package com.agent.vpsserver.common.utils.common;

import org.apache.http.util.TextUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @日 期: 2018/12/20 14:40:09
 * @描 述: 字符串工具类
 * 1、去除空格与制表符\t
 * 2、为空判断
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    private static final Pattern FORMAT_STR_PATTERN = Pattern.compile("\\s*|\t|\r|\n");

    /**
     * 去掉空格,换行和制表符
     *
     * @param str
     * @return
     */
    public static String formatStr(String str) {
        if (str != null && str.length() > 0) {
            Matcher m = FORMAT_STR_PATTERN.matcher(str);
            return m.replaceAll("");
        }
        return str;
    }

    /**
     * 去掉前后空格和制表符\t
     *
     * @param input
     * @return
     */
    public static String trim(String input) {
        if (null == input) {
            return null;
        }
        int len = input.length();
        int st = 0;
        char[] val = input.toCharArray();

        while ((st < len) && (val[st] <= ' ' || val[st] == '\t')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ' || val[st] == '\t')) {
            len--;
        }
        return ((st > 0) || (len < input.length())) ? input.substring(st, len) : input;
    }

    /**
     * 判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
     *
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {
        if (obj == null) {
            return true;
        }else if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length() == 0;
        }else if (obj instanceof Collection) {
            return ((Collection) obj).isEmpty();
        }else if (obj instanceof Map) {
            return ((Map) obj).isEmpty();
        }else if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

    /**
     * string转换成long
     * @param timestamp
     * @return
     */
    public static Long parseLong(String timestamp) {
        try{
            return Long.parseLong(timestamp);
        }catch (Exception ignored){
            return null;
        }
    }



    /**
     * map转String，用于同一规范加密，以key做升序排序
     *
     * @param map 参数map
     * @param separator 每对参数的连接符，例：http的&
     * @param join key-value的分隔符，例：=
     * @return
     */
    public static String mapToString(Map<String, Object> map, String join, String separator) {
        Iterator<String> keys = map.keySet().iterator();
        List<String> nameList = new ArrayList<String>();
        String key = null;
        // 过滤掉没有value的key
        while (keys.hasNext()) {
            key = keys.next();
            if (!TextUtils.isEmpty(map.get(key).toString())) {
                nameList.add(key);
            }
        }
        //参数升序
        nameList.sort((str1, str2) -> {
            if (str1.compareTo(str2) > 0) {
                return -1;
            } else if (str1.compareTo(str2) < 0) {
                return 1;
            } else {
                return 0;
            }
        });

        // 拼接字符串
        StringBuilder stringBuffer = new StringBuilder();
        String name = null;
        Object obj = null;
        for (int i = 0; i < nameList.size(); i++) {
            name = nameList.get(i);
            stringBuffer.append(name);
            stringBuffer.append(join);
            obj = map.get(name);
            if (!(obj instanceof Iterable) && !(obj instanceof Arrays)) {
                stringBuffer.append(obj.toString());
            }
            stringBuffer.append(separator);
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer.toString();
    }


    /**
     * 解析url请求参数
     * @param urlString url请求参数
     * @return
     */
    public static Map<String, String> getUrlParamsMap(String urlString) {
        return getUrlParamsMap(urlString, "UTF-8");
    }


    /**
     * 解析url请求参数
     * @param urlString url请求参数
     * @param enc 解析格式
     * @return
     */
    public static Map<String, String> getUrlParamsMap(String urlString, String enc) {
        if (urlString == null || urlString.length() == 0) {
            return Collections.EMPTY_MAP;
        }
        int questIndex = urlString.indexOf('?');
        if (questIndex == -1) {
            return Collections.EMPTY_MAP;
        }
        String url = urlString.substring(0, questIndex);
        String queryString = urlString.substring(questIndex + 1, urlString.length());
        Map paramsMap = new HashMap();
        if (queryString != null && queryString.length() > 0) {
            int ampersandIndex, lastAmpersandIndex = 0;
            String subStr, param, value;
            String[] paramPair, values;
            do {
                ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
                if (ampersandIndex > 0) {
                    subStr = queryString.substring(lastAmpersandIndex, ampersandIndex - 1);
                    lastAmpersandIndex = ampersandIndex;
                } else {
                    subStr = queryString.substring(lastAmpersandIndex);
                }
                paramPair = subStr.split("=");
                param = paramPair[0];
                value = paramPair.length == 1 ? "" : paramPair[1];
                try {
                    value = URLDecoder.decode(value, enc);
                    paramsMap.put(param, value);
                } catch (UnsupportedEncodingException ignored) {
                }
            } while (ampersandIndex > 0);
        }
        return paramsMap;
    }

    /**
     * 判断是否是纯数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        return StringUtils.isNumeric(str, true);
    }

    /**
     * 判断是否是数值
     * @param str
     * @param isNumber 是否是纯数字，false则可以有小数点和负号
     * @return
     */
    public static boolean isNumeric(String str, boolean isNumber){
        if (isNumber) {
            return org.apache.commons.lang3.StringUtils.isNumeric(str);
        } else {
            return str.matches("-?[0-9]+.?[0-9]*");
        }
    }
}

